import os
from datetime import datetime
import logging
from logging.handlers import TimedRotatingFileHandler
import platform
import threading
import psutil
import math
from prettytable import PrettyTable

_LOOK_FILE = f"{os.getcwd()}/RUNING.LOCK"


logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s  %(filename)s %(lineno)s: %(levelname)s  %(message)s %(threadName)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)

LOGGER = logging.getLogger(__name__)


def initApp():
    pass


def printEnvInfo():
    flask_env = os.environ.get("FLASK_ENV")
    pyVersion = platform.python_version()
    table = PrettyTable(["PyVersion", pyVersion])
    table.align["PyVersion"] = "r"
    table.align[pyVersion] = "l"

    uname = platform.uname()
    libInfo = _try_get_info()
    table.add_row(["DateTime", datetime.now()])
    table.add_row(["Os", uname.system + " " + uname.version + " " + uname.node])
    table.add_row(["CpuCount", libInfo["CpuCount"]])
    table.add_row(["Mem", libInfo["Mem"]])
    table.add_row(["FlaskEnv", flask_env])
    table.add_row(["pymysql", libInfo["pymysqlVersion"]])
    table.add_row(["redis", libInfo["redisVersion"]])
    table.add_row(["os.CurPwd", os.getcwd()])
    table.add_row(["Pid", os.getpid()])
    table.add_row(["ThreadId", threading.get_ident()])
    print(table)


def _try_get_info():
    info = {"pymysqlVersion": None, "redisVersion": None, "CpuCount": "-", "Mem": "-"}
    try:
        info["CpuCount"] = psutil.cpu_count(logical=False)
        info["Mem"] = f"{math.ceil(psutil.virtual_memory().total/1024/1024/1024)} GB"

    except Exception as e:
        pass
    try:
        import pymysql

        info["pymysqlVersion"] = pymysql.__version__
    except Exception as e:
        pass
    try:
        import redis

        info["redisVersion"] = redis.__version__
    except Exception as e:
        pass
    return info


def TRY_LOCK_RUNING():
    if os.path.exists(_LOOK_FILE):
        return False
    try:
        with open(_LOOK_FILE, "w") as f:
            f.write(f"{os.getpid()}")
        return True
    except Exception as e:
        print(e)
        return False


def _shutdown_hook():
    """关闭得时候，移除 lock 文件。"""
    """但有时候遇到恶劣退出，系统不会调用这里。启动得时候，需要手动删除lock。并手动确认，防止重复启动"""
    if os.path.exists(_LOOK_FILE):
        try:
            move_file = f'{_LOOK_FILE}.shutdown_at_{datetime.now().strftime("%Y_%m_%d_%H_%M_%S")}'
            os.rename(_LOOK_FILE, move_file)
        except Exception as e:
            pass


def ADD_SHUTDOWN_HOOK():
    import atexit

    atexit.register(_shutdown_hook)
